/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.home.fragment.me;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dataoke.shoppingguide.app773026.AppContext;
import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.util.ImageUtils;

import java.io.File;
import java.io.IOException;

import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;
/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class QRCodeDialog extends Dialog {

    private ImageView mIvCode;
    private TextView mTvQrcode;
    private TextView mTvLing;
    private Context context;

    public QRCodeDialog(Context context, @DrawableRes Integer resourceId) {
        this(context, R.style.App_Theme_Tweet_Main, resourceId);
    }

    @SuppressLint("InflateParams")
    private QRCodeDialog(final Context context, int defStyle, @DrawableRes Integer resourceId) {
        super(context, defStyle);
        this.context = context;
        View contentView = getLayoutInflater().inflate(
                R.layout.dialog_my_qr_code, null);
        mIvCode = contentView.findViewById(R.id.iv_qr_code);
        mTvQrcode = contentView.findViewById(R.id.tv_qrcode);
        mTvLing = contentView.findViewById(R.id.tv_ling);
        Object res;
        if(resourceId == R.mipmap.gzh) {
            mTvQrcode.setText("微信扫一扫，关注公众号");
            res = "https://shengqianapp.oss-cn-shanghai.aliyuncs.com/jkj/gzh.jpg";
        }else {
            mTvLing.setVisibility(View.GONE);
            res = resourceId;
        }

        Glide.with(context).asBitmap().load(res).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                mIvCode.setImageBitmap(resource);

            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mIvCode.setOnLongClickListener(v -> {
            if(EasyPermissions.hasPermissions(this.context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                dismiss();
                saveQrcode(context, res);
            } else {
                EasyPermissions.requestPermissions(
                        new PermissionRequest.Builder((Activity) this.context, 1, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .setRationale("需要开启" + getContext().getString(R.string.app_name) + "对您手机的存储权限才能保存二维码，是否现在开启")
                                .setPositiveButtonText("去开启")
                                .setNegativeButtonText("取消")
                                .setTheme(R.style.BaseTheme)
                                .build());
            }

            return false;
        });

        contentView.setOnTouchListener((v, event) -> {
            QRCodeDialog.this.dismiss();
            return false;
        });
        super.setContentView(contentView);
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        getWindow().setGravity(Gravity.CENTER);
        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = getWindow().getAttributes();
        p.width = ViewGroup.LayoutParams.MATCH_PARENT;
        p.height = ViewGroup.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(p);
    }

    protected void saveQrcode(Context context, Object resourceId) {
        String sdPath = context.getExternalFilesDir(Environment.DIRECTORY_DCIM) + File.separator +"jkj_qrcode" + System.currentTimeMillis()/1000 + ".png";
        File file = new File(sdPath);
        if (file.exists()) file.delete();
        Glide.with(context).asBitmap().load(resourceId).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                try {
                    ImageUtils.saveImageToSD(context, file.getAbsolutePath(), resource, 100);
                    AppContext.showToast("二维码已保存到相册");
                } catch (IOException e) {
                    e.printStackTrace();
                    AppContext.showToast("二维码保存失败");
                }

            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });


    }

}
